package com.yubest.demo;

import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.helpers.MessageFormatter;

import java.util.stream.Stream;

/**
 * json格式打印日志
 * @example: log.info("param: {}", obj);此时obj会显示成json格式
 * @Author: hweiyu
 * @Date: 2020/4/22 18:33
 * @Version: 1.0.0
 */
@Slf4j
public class JsonMessageConverter extends MessageConverter {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convert(ILoggingEvent event) {
        try {
            Object[] arr = Stream.of(event.getArgumentArray()).map(this::toJsonStr).toArray();
            return MessageFormatter.arrayFormat(event.getMessage(), arr).getMessage();
        } catch (Exception e) {
            return event.getMessage();
        }
    }

    private Object toJsonStr(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("json转换异常", e);
        }
        return obj;
    }

}
